package com.keter.common.security;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.keter.common.base.BaseController;
import com.keter.common.domain.user.UserController;
import com.keter.common.util.PasswordEncoderUtil;
import com.keter.framework.web.result.JSONResult;
import com.keter.framework.web.result.ResultUtil;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 认证token管理
 */
@RestController
@RequestMapping("/api/v1/security")
public class SecurityController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(SecurityController.class);
    @Autowired
    Security security;

    @Autowired
    UserController user;

    @ApiOperation(value = "根据用户（登录帐号）名获取用户：仅用于登录认证")
    @GetMapping("/username/{username}")
    public JSONResult findByUsername(
            @ApiParam(value = "用户名", required = true)
            @PathVariable String username){
//        logger.info("{}",request.getHeaderNames());
        return security.findUserByUsername(username);
    }

    @ApiOperation(value = "提供用户对象，生成Json Web Token")
    @PostMapping("/token/generate")
    public JSONResult generate(
            @ApiParam(value = "用户对象", required = true)
            @RequestBody String userDetails
    ) {
        JSONObject user = JSONObject.parseObject(userDetails);
        return wrap(security.generate(user));
    }

    @ApiOperation(value = "解析JWT：返回用户名")
    @GetMapping("/token/{token}/username")
    public JSONResult getUsername(@PathVariable String token) {
        return wrap(security.getUsername(token));
    }

    @ApiOperation(value = "解析JWT：返回用户对象")
    @GetMapping("/token/{token}/user")
    public JSONResult getUser(@PathVariable String token) {
        JSONResult result = wrap(security.getUser(token));
//        logger.info("result data:{}",result.data());
        return result;
    }

    @ApiOperation(value = "刷新JWT：为token续期")
    @GetMapping("/token/{token}/refresh")
    public JSONResult refresh(@PathVariable String token) {
        return wrap(security.refresh(token));
    }

    @ApiOperation(value = "刷新JWT：为token续期")
    @GetMapping("/token/{token}/refresh2")
    public JSONResult refreshResponse(@PathVariable String token) {
        JSONResult response = ResultUtil.wrap(security.refresh(token));
//        response.put("haha","hehe");
//        JSONResponse<String> response = new JSONResponse();
//        response.put(JSONResult.KEY_DATA, "haha");
//        response.put("hehe", "hehe");
        logger.info("response json:{}", JSON.toJSONString(response));
        return response;
//        return Response.wrap(security.refresh(token));
    }

    @ApiOperation(value = "重制JWT：根据现有token重新生成token，可用于内容对象变更后即时生效")
    @GetMapping("/token/{token}/regenerate")
    public JSONResult regenerate(@PathVariable String token, UserController user) {
        return wrap(security.regenerate(token,user));
    }

    @ApiOperation(value = "密码加密")
    @GetMapping("/encoder/{rawPassword}")
    public JSONResult encode(@PathVariable String rawPassword) {
        return wrap(PasswordEncoderUtil.encode(rawPassword));
    }


    @ApiOperation(value = "密码验证", notes = "由于加密出现的特殊字符(/)会影响URL中PathVariable的格式解析，因此采用param参数传递的方式")
    @GetMapping("/encoder")
    public JSONResult matches(
            @ApiParam(value = "明文", required = true)
            @RequestParam CharSequence rawPassword,
            @ApiParam(value = "密文", required = true)
            @RequestParam String encodedPassword) {
        return wrap(PasswordEncoderUtil.matches(rawPassword, encodedPassword));
    }
}
